package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.*;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 马迎迎
 * @Title: MallSearchServiecImpl
 * @Package com.atguigu.gulimall.search.service.impl
 * @Description: TODO(添加描述)
 * @date 2021年05月23日 10:26
 */
@Service
public class MallSearchServiecImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;
    @Override
    public SearchResult search(SearchParam searchParam) {
        //动态构建出查询需要的dsl语句
        SearchResult searchResult=null;
        //1.准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //2.执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            //3.分析响应数据，封装成我们需要的格式
            searchResult = buildSearchResult(searchParam,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 准备检索请求
     * #模糊匹配 过滤 排序 分页 高亮 聚合分析
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /**
         * 模糊匹配 过滤(按照属性 分类 品牌 价格区间 库存)
         */
        //1.构建bool query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1must
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2bool filter 按照三级分类id查询
        if(searchParam.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //1.2bool filter 按照品牌id查询
        if(searchParam.getBrandId()!=null&&searchParam.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.2bool filter 按照所有指定属性查询
        if(searchParam.getAttrs()!=null&&searchParam.getAttrs().size()>0){

            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attr=1_其他:安卓
                String[] s = attrStr.split("_");
                //检索的属性id
                String attrId=s[0];
                //检索的这个属性的所有值
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //每一个必须都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs",nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
            //attrs=1_其他:安卓&attrs=1_其他:安卓
        }
        //1.2bool filter 按照是否有库存查询
        if(searchParam.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock()==1));
        }


        //1.2bool filter 按照价格区间查询
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            //skuPrice=1_500/_500/500_
            /**
             * {
             *           "range": {
             *             "skuPrice": {
             *               "gte": 0,
             *               "lte": 5000
             *             }
             *           }
             *         }
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if(s.length==2){
                //区间
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if(s.length==1){
                if(searchParam.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[0]);
                }
                if(searchParam.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        //把以前的所有条件都拿来进行封装
        searchSourceBuilder.query(boolQuery);
        /**
         * 排序 分页 高亮
         */
        //2.1排序
        if(!StringUtils.isEmpty(searchParam.getSort())){
            //sort=hotScore_asc/desc
            String[] s = searchParam.getSort().split("_");
            SortOrder order=s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        //2.2分页
        /**
         *   "from": 0,
         *   "size": 20,
         *   from=(pageNum-1)*size
         */
        searchSourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3高亮
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //TODO 1.聚合品牌的信息
        searchSourceBuilder.aggregation(brand_agg);
        //2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        //分类聚合子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        //TODO 2.聚合catalog
        searchSourceBuilder.aggregation(catalog_agg);

        //3.属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //当前attrId的子聚合
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        attr_id_agg.subAggregation(attr_name_agg);
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50);
        attr_id_agg.subAggregation(attr_value_agg);

        attr_agg.subAggregation(attr_id_agg);
        //TODO 3.聚合属性信息
        searchSourceBuilder.aggregation(attr_agg);

        String string = searchSourceBuilder.toString();
        System.out.println("构建的dsl:"+string);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     */
    private SearchResult buildSearchResult(SearchParam searchParam,SearchResponse response) {
        SearchResult result = new SearchResult();
//        result.setProducts();//封装查询到的所有商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels=new ArrayList<>();
        if(hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel=JSON.parseObject(sourceAsString,SkuEsModel.class);
                if(!StringUtils.isEmpty(searchParam.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        //######以上从聚合信息中得到######//


//        result.setAttrs();//当前商品涉及的所有属性信息
        List<SearchResult.AttrVo> attrVos=new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            //得到属性名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //得到属性所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);



            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
//        result.setBrands();//当前商品涉及的所有品牌信息
        List<SearchResult.BrandVo> brandVos=new ArrayList<>();
        ParsedLongTerms brand_agg=response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {

            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            //得到品牌名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //得到品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
//        result.setCatalogs();//当前商品涉及的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos=new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            //得到分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //######以上从聚合信息中得到######//
        result.setPageNum(searchParam.getPageNum());//页码
        long total = hits.getTotalHits().value;
        result.setTotal(total);//总记录数
        int totalPages=(int)total%EsConstant.PRODUCT_PAGESIZE==0?(int)total/EsConstant.PRODUCT_PAGESIZE:((int)total%EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotalPages(totalPages);//总页数
        List<Integer> pageNavs=new ArrayList<>();
        for(int i=1;i<=totalPages;i++){

            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //构建面包屑导航功能
        if(searchParam.getAttrs()!=null){
            List<SearchResult.NavVo> navVos = searchParam.getAttrs().stream().map((attr) -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if(r.getCode()==0){
                    AttrResponceVO data = r.getData("attr",new TypeReference<AttrResponceVO>(){});
                    navVo.setNavName(data.getAttrName());

                }else {
                    navVo.setNavName(s[0]);
                }
                //2.取消了面包屑后 跳转到哪个地方 将请求地址的url置空
                String replace = replaceQueryString(searchParam, attr,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(navVos);
        }
        //品牌 分类
        if(searchParam.getBrandId()!=null&&searchParam.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //TODO 远程查询所有品牌
            R r = productFeignService.getBrandInfos(searchParam.getBrandId());
            if(r.getCode()==0){
                List<BrandEntity> brandEntities = r.getData("brand", new TypeReference<List<BrandEntity>>() {
                });
                StringBuffer buffer=new StringBuffer();
                String replace ="";
                for (BrandEntity brandEntity : brandEntities) {
                    buffer.append(brandEntity.getName()+";");
                    replace += replaceQueryString(searchParam, brandEntity.getBrandId()+"","brandId");
                }
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                navVo.setNavValue(buffer.toString());
            }
            navs.add(navVo);
        }
        //TODO 分类：不需要导航取消

        return result;
    }

    private String replaceQueryString(SearchParam searchParam, String value,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode.replace("+","%20");//浏览器对空格的编码和java不一样
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return searchParam.get_queryString().replace("&"+key+"=" + encode, "");
    }


}
